/**
 * WebSocket 客户端封装类
 * 提供自动重连、事件处理、消息发送等功能
 */
class WebSocketClient {
    /**
     * @param {string} url - WebSocket 服务器地址
     * @param {Object} options - 配置选项
     * @param {number} [options.maxReconnectAttempts=5] - 最大重连次数
     * @param {number} [options.reconnectInterval=3000] - 重连间隔(ms)
     */
    constructor(url, options = {}) {
        this.url = url
        this.options = options
        this.ws = null
        this.reconnectAttempts = 0
        this.maxReconnectAttempts = options.maxReconnectAttempts || 5
        this.reconnectInterval = options.reconnectInterval || 3000
        this.handlers = {
            message: new Set(),
            open: new Set(),
            close: new Set(),
            error: new Set()
        }
    }

    /**
     * 建立 WebSocket 连接
     */
    connect() {
        try {
            this.ws = new WebSocket(this.url)
            this.ws.onopen = () => this.handleOpen()
            this.ws.onclose = () => this.handleClose()
            this.ws.onerror = (error) => this.handleError(error)
            this.ws.onmessage = (event) => this.handleMessage(event)
        } catch (error) {
            console.error('WebSocket connection error:', error)
            this.handleError(error)
        }
    }

    handleOpen() {
        this.reconnectAttempts = 0
        this.handlers.open.forEach(handler => handler())
    }

    handleClose() {
        this.handlers.close.forEach(handler => handler())
        this.reconnect()
    }

    handleError(error) {
        this.handlers.error.forEach(handler => handler(error))
    }

    handleMessage(event) {
        try {
            const data = JSON.parse(event.data)
            this.handlers.message.forEach(handler => handler(data))
        } catch (error) {
            console.error('Failed to parse WebSocket message:', error)
        }
    }

    reconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++
            setTimeout(() => this.connect(), this.reconnectInterval)
        }
    }

    /**
     * 发送数据到服务器
     * @param {string|Object} data - 要发送的数据
     */
    send(data) {
        if (this.ws?.readyState === WebSocket.OPEN) {
            this.ws.send(typeof data === 'string' ? data : JSON.stringify(data))
        } else {
            console.error('WebSocket is not connected')
        }
    }

    /**
     * 注册事件处理器
     * @param {'message'|'open'|'close'|'error'} event - 事件类型
     * @param {Function} handler - 事件处理函数
     */
    on(event, handler) {
        if (this.handlers[event]) {
            this.handlers[event].add(handler)
        }
    }

    off(event, handler) {
        if (this.handlers[event]) {
            this.handlers[event].delete(handler)
        }
    }

    close() {
        if (this.ws) {
            this.ws.close()
            this.ws = null
        }
    }
}

export default WebSocketClient 